<template>
  <div class="employee-container">
    <PageHeader title="员工管理">
      <template #actions>
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          添加员工
        </el-button>
      </template>
    </PageHeader>

    <main class="employee-content">
      <el-card>
        <template #header>
          <div class="card-header">
            <div class="filter-section">
              <el-input
                v-model="searchQuery"
                placeholder="搜索员工姓名/工号"
                :prefix-icon="Search"
                style="width: 200px; margin-right: 16px"
                clearable
              />
              <el-select
                v-model="departmentFilter"
                placeholder="选择部门"
                clearable
                style="width: 160px; margin-right: 16px"
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
              <el-select
                v-model="statusFilter"
                placeholder="在职状态"
                clearable
                style="width: 120px"
              >
                <el-option label="在职" value="active" />
                <el-option label="离职" value="inactive" />
              </el-select>
            </div>
            <el-button :icon="RefreshLeft" @click="fetchEmployees">
              刷新
            </el-button>
          </div>
        </template>

        <el-table :data="filteredEmployees" style="width: 100%">
          <el-table-column prop="employee_id" label="工号" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="position" label="职位" width="120" />
          <el-table-column prop="phone" label="联系电话" width="140" />
          <el-table-column prop="email" label="邮箱" min-width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'info'">
                {{ row.status === 'active' ? '在职' : '离职' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-button
                  size="small"
                  :icon="View"
                  @click="handleView(row)"
                >
                  查看
                </el-button>
                <el-button
                  size="small"
                  type="primary"
                  :icon="Edit"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  :icon="Delete"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </main>

    <!-- 员工表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑员工' : '添加员工'"
      width="500px"
    >
      <el-form
        ref="employeeFormRef"
        :model="employeeForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="工号" prop="employee_id">
          <el-input v-model="employeeForm.employee_id" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" />
        </el-form-item>
        <el-form-item label="部门" prop="department_id">
          <el-select v-model="employeeForm.department_id" style="width: 100%">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
          <!-- 调试信息 -->
          <div style="color: #999; font-size: 12px; margin-top: 5px;">
            选中的部门ID: {{ employeeForm.department_id }}
            <br>
            可用部门: {{ departments.map(d => ({ id: d.id, name: d.name })) }}
          </div>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="employeeForm.position" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="employeeForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="employeeForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入员工描述信息"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="employeeForm.status" style="width: 100%">
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="handleSave">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看员工详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="员工详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工号">{{ selectedEmployee.employee_id }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ selectedEmployee.name }}</el-descriptions-item>
        <el-descriptions-item label="部门">
          {{ departments.find(d => d.id === selectedEmployee.department_id)?.name }}
        </el-descriptions-item>
        <el-descriptions-item label="职位">{{ selectedEmployee.position }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ selectedEmployee.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ selectedEmployee.email || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">
          <el-tag :type="selectedEmployee.status === 'active' ? 'success' : 'info'">
            {{ selectedEmployee.status === 'active' ? '在职' : '离职' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ selectedEmployee.description || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, RefreshLeft, View, Edit, Delete } from '@element-plus/icons-vue'
import PageHeader from '@/components/PageHeader.vue'
import api from '@/services/api'

// 状态定义
const employees = ref([])
const departments = ref([])
const searchQuery = ref('')
const departmentFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const employeeFormRef = ref(null)
const detailsDialogVisible = ref(false)
const selectedEmployee = ref({})

// 表单数据
const employeeForm = reactive({
  employee_id: '',
  name: '',
  department_id: '',
  position: '',
  phone: '',
  email: '',
  description: '', // 新增描述字段
  status: 'active'
})

// 表单验证规则
const rules = {
  employee_id: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  department_id: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 初始化
onMounted(() => {
  fetchEmployees()
  fetchDepartments()
})

// 计算属性
const filteredEmployees = computed(() => {
  return employees.value.map(employee => {
    const dept = departments.value.find(d => d.id === employee.department_id)
    return {
      ...employee,
      department: dept ? dept.name : ''
    }
  })
})

// 方法定义
const fetchEmployees = async () => {
  try {
    const filters = {
      department_id: departmentFilter.value || undefined,
      status: statusFilter.value || undefined,
      search: searchQuery.value || undefined
    }

    const response = await api.getEmployees(currentPage.value, pageSize.value, filters)
    employees.value = response.data.employees
    total.value = response.data.total
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  }
}

const fetchDepartments = async () => {
  try {
    console.log('开始获取部门列表')
    const response = await api.getDepartments()
    console.log('部门列表响应:', response)
    departments.value = response.data.departments || []
    console.log('当前部门列表:', departments.value)
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

const resetForm = () => {
  employeeForm.employee_id = ''
  employeeForm.name = ''
  employeeForm.department_id = ''
  employeeForm.position = ''
  employeeForm.phone = ''
  employeeForm.email = ''
  employeeForm.description = ''
  employeeForm.status = 'active'
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(employeeForm, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  selectedEmployee.value = { ...row }
  detailsDialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该员工吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await api.deleteEmployee(row.id)
      ElMessage.success('删除成功')
      fetchEmployees()
    } catch (error) {
      console.error('删除员工失败:', error)
      ElMessage.error(error.response?.data?.error || '删除员工失败')
    }
  }).catch(() => {})
}

const handleSave = async () => {
  if (!employeeFormRef.value) return

  try {
    await employeeFormRef.value.validate()
    saving.value = true

    // 调试信息
    console.log('提交的表单数据:', JSON.stringify(employeeForm))
    console.log('部门ID类型:', typeof employeeForm.department_id)

    // 确保 department_id 是数字
    if (employeeForm.department_id && typeof employeeForm.department_id === 'string') {
      employeeForm.department_id = parseInt(employeeForm.department_id, 10)
    }

    if (isEdit.value) {
      const response = await api.updateEmployee(employeeForm.id, employeeForm)
      console.log('更新响应:', response)
      ElMessage.success('更新成功')
    } else {
      const response = await api.createEmployee(employeeForm)
      console.log('创建响应:', response)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    fetchEmployees()
  } catch (error) {
    console.error('保存员工失败:', error)
    ElMessage.error(error.response?.data?.error || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEmployees()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployees()
}
</script>

<style scoped>
.employee-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.employee-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-descriptions__cell) {
  padding: 12px !important;
}

:deep(.el-descriptions__label) {
  width: 120px;
  color: #606266;
}
</style>

